﻿using System.Runtime.InteropServices;

namespace TDMS.Net.Internals;

internal sealed class PinnedStringArray : IDisposable
{
    private readonly IntPtr[] _ptrs;
    private GCHandle _gch;

    public PinnedStringArray(string[] array)
    {
        _ptrs = array.Select(Marshal.StringToCoTaskMemUTF8).ToArray();
        _gch = GCHandle.Alloc(_ptrs, GCHandleType.Pinned);
    }

    public IntPtr PinnedPtr => _gch.AddrOfPinnedObject();

    private void ReleaseUnmanagedResources()
    {
        _gch.Free();

        foreach (var p in _ptrs)
        {
            Marshal.FreeCoTaskMem(p);
        }
    }

    public void Dispose()
    {
        ReleaseUnmanagedResources();
        GC.SuppressFinalize(this);
    }

    ~PinnedStringArray()
    {
        ReleaseUnmanagedResources();
    }
}